//
//  GroupSettingViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/3/13.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "GroupSettingViewController.h"
#import "NIMCardMemberItem.h"
#import "GroupSearchRecordVC.h"
#import "NTESBundleSetting.h"
#import "ChatServer.h"
#import "NIMTeamMemberListViewController.h"
#define kGroupHeadW AdaptedWidth(42)
@interface GroupSettingViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UICollectionView*headClvView;
@property (nonatomic,strong) NSMutableArray*dataMembers;
@property (nonatomic,strong)  NIMSession *session;
@property (nonatomic,strong) ChatServer*chatServer;

@end

@implementation GroupSettingViewController
- (instancetype)initWithSession:(NIMSession *)session{
    if (self == [super init]) {
        self.session = session;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self getMemebers];
}

- (void)getMemebers{
    [[NIMSDK sharedSDK].teamManager fetchTeamMembers:self.session.sessionId completion:^(NSError * _Nullable error, NSArray<NIMTeamMember *> * _Nullable members) {
        [members enumerateObjectsUsingBlock:^(NIMTeamMember * _Nonnull member, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.dataMembers addObject:[[NIMTeamCardMemberItem alloc] initWithMember:member]];
        }];
        self.headClvView.height = self.dataMembers.count>5?AdaptedWidth(160):AdaptedWidth(100);
        [self.headClvView reloadData];
        [self.tableView reloadData];
    }];
}

- (void)setupUI{
    self.title = XLocalized(@"群组信息");
    self.tableView.tableHeaderView = self.headClvView;
    self.tableView.backgroundColor = UIColorHex(#F7F7F7);
    [self.headClvView registerClass:UICollectionReusableView.class forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footIdentifier"];
    self.tableView.contentInset = UIEdgeInsetsMake(-AdaptedWidth(30), 0, 0, 0);
    kWeakSelf(self);
    LMJWordArrowItem *item1 = [LMJWordArrowItem itemWithTitle:XLocalized(@"查找聊天记录") subTitle: @""];
    item1.cellHeight = AdaptedWidth(50);
    item1.itemOperation = ^(NSIndexPath *indexPath) {
        GroupSearchRecordVC *vc = [[GroupSearchRecordVC alloc]initWithSession:weakself.session];
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    LMJWordArrowItem *item2 = [LMJWordArrowItem itemWithTitle:XLocalized(@"清空聊天记录") subTitle: @""];
    item2.cellHeight = AdaptedWidth(50);
    item2.itemOperation = ^(NSIndexPath *indexPath) {
        [LEEAlert actionsheet].config
        .LeeTitle([NSString stringWithFormat:@"%@?",XLocalized(@"清空聊天记录")])
        .LeeDestructiveAction(XLocalized(@"确认"), ^{
            BOOL removeRecentSession = [NTESBundleSetting sharedConfig].removeSessionWhenDeleteMessages;
            BOOL removeTable = [NTESBundleSetting sharedConfig].dropTableWhenDeleteMessages;
            NIMDeleteMessagesOption *option = [[NIMDeleteMessagesOption alloc] init];
            option.removeSession = removeRecentSession;
            option.removeTable = removeTable;
            [[NIMSDK sharedSDK].conversationManager deleteAllmessagesInSession:self.session
                                                                        option:option];
            [weakself.view makeToast:XLocalized(@"清除成功！")];
        })
        .LeeCancelAction(XLocalized(@"取消"),nil)
        .LeeShow();
    };
    LMJItemSection *section = [LMJItemSection sectionWithItems:@[item1,item2] andHeaderTitle:nil footerTitle:nil];
    [self.sections addObject:section];
    
    UIView*bottomBack = [UIView new];
    bottomBack.backgroundColor = UIColorHex(#E6E6E6);
    UIButton *bottomBtn = [UIButton new];
    [bottomBtn setTitleColor:UIColorHex(#000000) forState:UIControlStateNormal];
    [bottomBtn setTitle:XLocalized(@"删除并退出") forState:UIControlStateNormal];
    bottomBtn.titleLabel.font = kDefaultFont(17);
    [self.view addSubview:bottomBack];
    [bottomBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(kTabBarHeight);
    }];
    [bottomBack addSubview:bottomBtn];
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    
    [bottomBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [LEEAlert actionsheet].config
        .LeeTitle([NSString stringWithFormat:@"%@?",XLocalized(@"删除并退出")])
        .LeeDestructiveAction(XLocalized(@"确认"), ^{
            [MBProgressHUD showLoadTitile:@"" ToView:self.view];
            [self.chatServer deleteChatroom:self.session.sessionId completion:^(BOOL success, NSString * _Nonnull msg) {
                [MBProgressHUD hideHUDForView:self.view];
                if (success) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }else{
                    [self.view makeToast:msg];
                }
            }];
           
        })
        .LeeCancelAction(XLocalized(@"取消"), nil)
        .LeeShow();
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return AdaptedWidth(13);
}

#pragma mark - delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataMembers.count>10?10:self.dataMembers.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headCellIdentifier" forIndexPath:indexPath];
    UIImageView*headImgV =  [cell.contentView viewWithTag:1000];
    if (!headImgV) {
        headImgV = [UIImageView new];
        headImgV.tag=1000;
        [cell.contentView addSubview:headImgV];
        [headImgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
        ViewRadius(headImgV, AdaptedWidth(10));
    }
    NIMTeamCardMemberItem *item = [self.dataMembers objectOrNilAtIndex:indexPath.item];
    [headImgV sd_setImageWithURL:String_To_URL(item.imageUrl) placeholderImage:item.imageNormal];;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        UICollectionReusableView* footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footIdentifier" forIndexPath:indexPath];
        UIButton *moreBtn = [footView viewWithTag:1000];
        if (!moreBtn) {
            moreBtn = [[UIButton alloc] init];
            moreBtn.tag = 1000  ;
            [moreBtn setTitle:XLocalized(@"查看更多群成员>") forState:UIControlStateNormal];
            [moreBtn setTitleColor:UIColorHex(#999999) forState:UIControlStateNormal];
            moreBtn.titleLabel.font = kDefaultFont(12);
            [footView addSubview:moreBtn];
            [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.centerY.mas_equalTo(0);
            }];
            kWeakSelf(self);
            [moreBtn addTapBlock:^(UIButton * _Nonnull btn) {
                NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:weakself.session.sessionId];
                NIMTeamMemberListViewController *vc = [[NIMTeamMemberListViewController alloc] initTeam:team members:weakself.dataMembers];
                [weakself.navigationController pushViewController:vc animated:YES];
            }];
        }
        
        return footView;
    }else{
        return nil;
    }
}

#pragma mark - getter
- (UICollectionView*)headClvView{
    if (!_headClvView) {
       UICollectionViewFlowLayout* flowLayout = [UICollectionViewFlowLayout new];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        flowLayout.itemSize = CGSizeMake(kGroupHeadW, kGroupHeadW);
        flowLayout.minimumLineSpacing= AdaptedWidth(16);
        flowLayout.minimumInteritemSpacing = ((kScreenWidth-AdaptedWidth(32))-5*kGroupHeadW)/4;
        flowLayout.footerReferenceSize = CGSizeMake(0, AdaptedWidth(50));
        _headClvView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _headClvView.dataSource = self;
        _headClvView.delegate = self;
        [_headClvView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"headCellIdentifier"];
        _headClvView.scrollEnabled = NO;
        _headClvView.showsVerticalScrollIndicator = NO;
        _headClvView.showsHorizontalScrollIndicator = NO;
        _headClvView.backgroundColor = [UIColor whiteColor];
        _headClvView.contentInset = UIEdgeInsetsMake(AdaptedWidth(13), AdaptedWidth(16), AdaptedWidth(13), AdaptedWidth(16));
    }
    return _headClvView;
}

- (NSMutableArray*)dataMembers{
    if (!_dataMembers) {
        _dataMembers = [NSMutableArray array];
    }
    return _dataMembers;
}

#pragma - mark getter
- (ChatServer*)chatServer{
    if (!_chatServer) {
        _chatServer = [ChatServer new];
    }
    return _chatServer;
}
@end
